package auth

import (
	config2 "gin-cli/utils/config"
	"github.com/dgrijalva/jwt-go"
	"time"
)

/**
* Title: jwt编码
* Author: lauwen
* E-mail: me@luxuewen.com
 */
func JwtEncode (userinfo interface{}, key string) (string, error) {
	second := time.Duration(config2.Get("config.apiTokenExpireTime").(int))

	token, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
		"tokenInfo": userinfo,
		"exp": time.Now().Add(time.Second * second).Unix(),
	}).SignedString([]byte(key))

	if err != nil {
		return "", err
	}
	return token, nil
}

/**
* Title:jwt解码
* Author: lauwen
* E-mail: me@luxuewen.com
 */
func JwtDecode (token, key string) (map[string]interface{}, int64, error) {
	claim, err := jwt.Parse(token, func(token *jwt.Token) (interface{}, error) {
		return []byte(key), nil
	})

	if err != nil {
		return nil, 0, err
	}

	exp := int64(claim.Claims.(jwt.MapClaims)["exp"].(float64))
	tokenInfo := claim.Claims.(jwt.MapClaims)["tokenInfo"].(map[string]interface{})
	return tokenInfo, exp, nil
}
